package com.lzh.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lzh.common.to.es.SkuEsModel;
import com.lzh.common.utils.R;
import com.lzh.gulimall.search.config.GulimallElasticSearchConfig;
import com.lzh.gulimall.search.constant.EsConstant;
import com.lzh.gulimall.search.feign.ProductFeignService;
import com.lzh.gulimall.search.service.MallSearchService;
import com.lzh.gulimall.search.vo.AttrResponseVo;
import com.lzh.gulimall.search.vo.SearchParam;
import com.lzh.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.swing.text.Highlighter;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName MallSearchServiceImpl
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/8/27 23:12
 * @Version 1.0
 **/
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;


    /**
     * ES检索
     * @param searchParam 检索的所有参数
     * @return
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        //结果数据
        SearchResult searchResult=null;
        try {
            //1、动态构建出查询需要的DSL语句
            //创建检索请求
            SearchRequest searchRequest = buildSearchRequest(searchParam);

            //2、执行检索
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            //3、分析响应数据封装成我们需要的格式
            searchResult=buildSearchResult(response,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }
    /**
     * 构建检索请求
     * 模糊匹配，过滤(按照属性，分类，平拍，价格区间，库存),排序，分页，高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //构建DSL语句
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        /**
         * 模糊匹配，过滤(按照属性，分类，平拍，价格区间，库存)
         */
        //1.构建bool - query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1、must - 模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2、bool - filter - 按照三级分类id查询
        if (searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //1.3、bool - filter - 按照品牌id查询
        if (searchParam.getBrandId()!=null && searchParam.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.4、bool - filter - 按照是否有货查询
        if (searchParam.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock()==1));
        }
        //1.5、bool - filter - 按照价格区间查询查询
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            /**
             * 价格区间查询
             * 1_500 就是1<skuPrice<500
             * _500就是skuPrice<500
             * 500_就是skuPrice>500
             */
            String skuPrice = searchParam.getSkuPrice();
            String[] s = skuPrice.split("_");
            //区间
            if (s.length==2){
                //gte大于  lte小于
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }else if (s.length==1){
                if (searchParam.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")) {
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //1.6、bool - filter - 按照属性进行筛选
        if (searchParam.getAttrs()!=null && searchParam.getAttrs().size()>0){
            //attrs=1_5寸:8寸&attrs=2_16G:8G
            //1号属性5寸和8寸
            //2号属性16G和8G
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                //attr=1_5寸:8寸
                String[] s = attr.split("_");
                //属性id
                String attrId=s[0];
                //属性值
                String[] attrValues = s[1].split(":");
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId ));
                boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //ScoreMode.None不参与评分
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }
        //把之前设置的条件进行封装
        sourceBuilder.query(boolQueryBuilder);
        /**
         * 排序，分页，高亮
         */
        //2.1、sort
        if (! StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            //sort=hotScore_asc/desc
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //2.2、分页
        //from=（pagenum-1）*size
        sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3、高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }
        /**
         * 聚合分析
         */
        //3.1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_Name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //聚合品牌
        sourceBuilder.aggregation(brand_agg);
        //3.2、分类聚合 当前查询到的商品属于那些分类
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(10);
        //分类聚合的子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        //聚合分类
        sourceBuilder.aggregation(catalog_agg);
        //3.3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前attrId对应的名字
        TermsAggregationBuilder att_name_agg = AggregationBuilders.terms("att_name_agg").field("attrs.attrName").size(1);
        //聚合分析出当前attrId可能的属性值
        TermsAggregationBuilder att_value_agg = AggregationBuilders.terms("att_value_agg").field("attrs.attrValue").size(50);
        attr_id_agg.subAggregation(att_name_agg);
        attr_id_agg.subAggregation(att_value_agg);
        attr_agg.subAggregation(attr_id_agg);
        //聚合属性
        sourceBuilder.aggregation(attr_agg);

        //查看DSL语句
        System.out.println("构建的DSL语句："+sourceBuilder.toString());
        //构建检索请求
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
    /**
     * 构建结果数据
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();

        //1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        ArrayList<SkuEsModel> list = new ArrayList<>();
        if (hits.getHits()!=null && hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                //获取到数据，json格式
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //按关键字检索的，需要高亮
                if (!StringUtils.isEmpty(searchParam.getKeyword())){
                    //获取高亮
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                list.add(skuEsModel);
            }
        }
        searchResult.setProduct(list);

        //2、当前所有商品涉及到的所有属性信息
        ArrayList<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo=new SearchResult.AttrVo();
            //设置属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //设置属性名
            String attName = ((ParsedStringTerms) bucket.getAggregations().get("att_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attName);
            //设置属性值
            ParsedStringTerms parsedStringTerms = (ParsedStringTerms) bucket.getAggregations().get("att_value_agg");
            List<String> values=new ArrayList<>();
            for (Terms.Bucket parsedStringTermsBucket : parsedStringTerms.getBuckets()) {
                String keyAsString = parsedStringTermsBucket.getKeyAsString();
                values.add(keyAsString);
            }
            attrVo.setAttrValue(values);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);

        //3、当前所有商品涉及到的所有品牌信息
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo=new SearchResult.BrandVo();
            //获取品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            //获取品牌名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_Name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            //获取品牌图片
            String brandImg= ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg"))
                    .getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        //4、当前所有品牌涉及到的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo=new SearchResult.CatalogVo();
            //获取分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(keyAsString));
            //获取子聚合，得到分类名
            ParsedStringTerms parsedStringTerms = bucket.getAggregations().get("catalog_name_agg");
            //获取其分类名
            String keyAsString1 = parsedStringTerms.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(keyAsString1);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        //5、分页信息、页码
        searchResult.setPageNum(searchParam.getPageNum());

        //6、分页信息-总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);

        //7、分页信息-总页码
        int totalPages=(int)total%EsConstant.PRODUCT_PAGESIZE==0?(int)total/EsConstant.PRODUCT_PAGESIZE:((int)total/EsConstant.PRODUCT_PAGESIZE)+1;
        searchResult.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 0; i < totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);


        //8、构建面包屑导航
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = (AttrResponseVo) r.getData("attr", new TypeReference<AttrResponseVo>() {});
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = searchParam.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            searchResult.setNavs(collect);
        }


        return searchResult;
    }
}
